'use client';

import type { INginxKey } from '@/interfaces';
import { deleteNginxKey } from '@/services/api';
import { useMutation } from '@tanstack/react-query';
import { type FormEvent } from 'react';
import useToast from '@/hooks/useToast';
import Box from '@/app/[locale]/admin/common/box';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';
import { useRouter } from 'next/navigation';

export default function DeleteNginxConfigKeyPage({
  source,
  translatedFields,
}: {
  source: INginxKey;
  translatedFields: PrefixedTTranslatedFields<'logAdminPage'>;
}) {
  const { show } = useToast();
  const router = useRouter();

  const deleteNginxKeyMutation = useMutation(deleteNginxKey);

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const id = source.id;
      await deleteNginxKeyMutation.mutateAsync({
        id,
      });

      show({
        type: 'SUCCESS',
        message: translatedFields.deleteCompleted,
      });

      setTimeout(() => {
        show({
          type: 'SUCCESS',
          message: translatedFields.returning,
        });
      }, 1200);

      setTimeout(() => {
        router.back();
      }, 1500);
    } catch (e) {
      deleteNginxKeyMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  return (
    <Box>
      <div className="card">
        <div className="card-body">
          <form
            onSubmit={onSubmit}
            className="vstack gap-4 align-items-center py-4"
          >
            <div className="text-center">
              <span>{translatedFields.deletePlaceholder}&nbsp;</span>
              <span className="fw-semibold text-danger lead">{`⌈ ${
                source.secret
              } (REMARK. ${source.remark ?? ''}, USED. ${
                source.used + ''
              }) ⌋`}</span>
            </div>
            <button
              type="submit"
              disabled={deleteNginxKeyMutation.isLoading}
              className="btn btn-danger col col-lg-2 mt-4"
            >
              {deleteNginxKeyMutation.isLoading && <Spinner classs="me-2" />}
              {translatedFields.delete}
            </button>
          </form>
        </div>
      </div>
    </Box>
  );
}
